package com.hefei.garden.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: devil
 * @Date: 2022/9/11 13
 * @Description: redis bloom过滤器配置
 */
@Component
public class BloomFilterConfig {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Boolean bloomFilterAdd(String filterName, int value) {
        DefaultRedisScript<Boolean> bloomAdd = new DefaultRedisScript<>();
        bloomAdd.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis-lua/bloomFilterAdd.lua")));
        bloomAdd.setResultType(Boolean.class);
        List<String> keyList = new ArrayList<>();
        keyList.add(filterName);
        keyList.add(value + "");
        return redisTemplate.execute(bloomAdd, keyList);
    }

    public Boolean bloomFilterExists(String filterName, int value) {
        DefaultRedisScript<Boolean> bloomExists = new DefaultRedisScript<>();
        bloomExists.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis-lua/bloomFilterExist.lua")));
        bloomExists.setResultType(Boolean.class);
        List<String> keyList = new ArrayList<>();
        keyList.add(filterName);
        keyList.add(value + "");
        return redisTemplate.execute(bloomExists, keyList);
    }

}
